package models

import (
	"github.com/shopspring/decimal"
	"gorm.io/gorm"
	"mojieshi/define"
	"strconv"
	"strings"
	"time"
)

type MRegisterGiveset struct {
	ID           int             `gorm:"type:int(10); primaryKey" json:"id"`
	Aid          int             `gorm:"type:int(10);" json:"aid"`             //账户ID
	Money        decimal.Decimal `json:"money"`                                //赠送余额
	Score        int             `gorm:"type:int(10);" json:"score"`           //赠送积分
	WanshanScore int             `gorm:"type:int(10);" json:"wanshan_score"`   //完善资料送积分
	GiveCoupon   int             `gorm:"type:int(10);" json:"give_coupon"`     //赠送优惠券开启 1:开启 0关闭
	CouponIds    string          `gorm:"type:varchar(255);" json:"coupon_ids"` //优惠券id
	Starttime    int             `gorm:"type:int(10);" json:"starttime"`       //开始时间
	Endtime      int             `gorm:"type:int(10);" json:"endtime"`         //结束时间
	Status       int             `gorm:"type:int(10);" json:"status"`          //状态 1:开启 0关闭
	Createtime   int             `gorm:"type:int(10);" json:"createtime"`
}

func (table *MRegisterGiveset) TableName() string {
	return "m_register_giveset"
}

// 注册营销
func RegisterGivest(tx *gorm.DB, Aid int, Mid int) error {
	//查询营销数据
	var data MRegisterGiveset
	err := tx.Model(new(MRegisterGiveset)).Where("aid=?", Aid).First(&data).Error
	if err != nil {
		return err
	}
	//判断是否开启了活动
	if data.Status == 1 {
		//获取开始时间和结束时间
		//获取当前时间
		nowTime := time.Now().Unix()
		//判断是否已经开始活动并且活动还未结束
		if nowTime >= int64(data.Starttime) && nowTime <= int64(data.Endtime) {
			//为用户增加余额和积分
			upData := map[string]interface{}{
				"score": gorm.Expr("score+?", data.Score),
				"money": gorm.Expr("money+?", data.Money),
			}
			err = tx.Model(new(MMember)).Where("aid=? AND id=?", Aid, Mid).Updates(&upData).Error
			if err != nil {
				return err
			}
			//写入积分记录
			scoreData := map[string]interface{}{
				"aid":        Aid,
				"mid":        Mid,
				"score":      data.Score,
				"after":      data.Score,
				"createtime": int(time.Now().Unix()),
				"remark":     "注册赠送",
				"type":       1,
				"status":     0,
				"is_cancel":  0,
			}
			err = tx.Model(new(MMemberScorelog)).Create(&scoreData).Error
			if err != nil {
				return err
			}
			//写入余额记录
			moneyData := map[string]interface{}{
				"aid":        Aid,
				"mid":        Mid,
				"money":      data.Money,
				"after":      data.Money,
				"createtime": int(time.Now().Unix()),
				"remark":     "注册赠送",
				"type":       1,
			}
			err = tx.Model(new(MMemberMoneylog)).Create(&moneyData).Error
			if err != nil {
				return err
			}
			//判断是否写入优惠券
			if data.GiveCoupon == 1 {
				list := strings.Split(data.CouponIds, ",")
				for i := 0; i < len(list); i++ {
					couId, _ := strconv.Atoi(list[i])
					var couponData MCoupon
					err = tx.Model(new(MCoupon)).Where("id=?", couId).First(&couponData).Error
					if err != nil {
						return err
					}
					//生成随机码
					var RandomStr string
					RandomStr = string(define.Krand(16, define.KC_RAND_KIND_ALL))
					couponData1 := map[string]interface{}{
						"aid":        Aid,
						"mid":        Mid,
						"bid":        couponData.Bid,
						"couponid":   couId,
						"couponname": couponData.Name,
						"money":      couponData.Money,
						"minprice":   couponData.Minprice,
						"starttime":  couponData.Starttime,
						"endtime":    couponData.Endtime,
						"createtime": int(time.Now().Unix()),
						"status":     0,
						"type":       couponData.Type,
						"used_count": 0,
						"code":       RandomStr,
						"hexiaoqr":   "hhhhhh",
					}
					if couponData.Yxqtype == 2 {
						couponData1["usetime"] = int(int64(couponData.Yxqdate*86400) + time.Now().Unix())
					} else {
						couponData1["usetime"] = couponData.YxqendTime
					}
					err = tx.Model(new(MCouponRecord)).Create(&couponData1).Error
					if err != nil {
						return err
					}
				}
			}
		}
	}
	return nil
}
